<script lang="ts" setup>
import { ref } from "vue";
import type { LoginForm } from "@/typings/api";
import { NForm, NFormItem, NInput, NButton, type FormInst, type FormRules } from "naive-ui";
import { useUserStore } from "@/stores/module/user";
import { usePermissionStore } from "@/stores/module/permission";
import { useDesignStore } from "@/stores/module/design";
import { useRouter } from "vue-router";

const router = useRouter();

const { getPrefixCls } = useDesignStore();

const prefixCls = getPrefixCls("login");

const userStore = useUserStore();
userStore.getCaptcha();

const permissionStore = usePermissionStore();

const formRef = ref<FormInst | null>(null);
const rules: FormRules = {
  username: {
    required: true,
    message: "请输入密码",
    trigger: "blur",
  },
  password: {
    required: true,
    message: "请输入密码",
    trigger: "blur",
  },
  captcha: {
    required: true,
    message: "请输入验证码",
    trigger: "blur",
  },
};
const formValue = ref<LoginForm>({
  username: "admin",
  password: "admin",
  captcha: "",
  captchaId: userStore.currentCaptchaId,
});

const login = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errs) => {
    if (errs) return;
    await userStore.login(formValue.value);
    await permissionStore.getPermissionTree();
    router.push({ name: "console" });
  });
};
</script>

<template>
  <div :class="`${prefixCls}-password`">
    <h2 :class="`${prefixCls}-password__title`">VUE TEMPLATE</h2>
    <NForm ref="formRef" :model="formValue" :rules="rules" size="large" label-placement="left">
      <NFormItem path="username">
        <NInput v-model:value="formValue.username" placeholder="请输入用户名" />
      </NFormItem>
      <NFormItem path="password">
        <NInput v-model:value="formValue.password" placeholder="请输入密码" />
      </NFormItem>
      <NFormItem path="captcha">
        <div class="flex w-full gap-5">
          <NInput v-model:value="formValue.captcha" placeholder="请输入验证码" />
          <div
            class="cursor-pointer"
            style="height: 40px"
            v-html="userStore.captchaDomString"
            @click="userStore.getCaptcha()"
          ></div>
        </div>
      </NFormItem>
      <NFormItem>
        <NButton class="w-full" attr-type="button" @click="login">登录</NButton>
      </NFormItem>
    </NForm>
  </div>
</template>

<style lang="less" scoped>
@prefix-cls: ~"@{namespace}-login-password";
.@{prefix-cls} {
  @apply w-112 h-120 flex flex-col border-rd-2 px-7.5 py-2.5;
  box-shadow: 0 1px 2px -2px #00000029, 0 3px 6px #0000001f, 0 5px 12px 4px #00000017;

  &__title {
    @apply mt-7.5 mb-20 text-center;
  }
}
</style>
